package com.zbkj.crmeb.open;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Lists;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.request.PushOrderStoreRequest;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import com.zbkj.crmeb.user.service.UserAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crmeb.core.common.CommonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.List;


/**
 * 商品表 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("api/open/store/order")
@Api(tags = "订单") //配合swagger使用
public class OpenStoreOrderApiController {
    @Autowired
    StoreOrderService storeOrderService;

    @Autowired
    StoreOrderInfoService storeOrderInfoService;

    /**
     * 查询最新支付订单
     * @param startTime 订单支付开始时间
     */
    @ApiOperation(value = "导入订单id")
    @RequestMapping(value = "/queryOrderIds", method = RequestMethod.GET)
    public CommonResult<List<String>> queryOrderIds(@RequestParam(value = "startTime") String startTime){
        // 默认取全部订单
        if(StringUtils.isBlank(startTime)){
            return CommonResult.failed("请输入查询开始时间!");
        }
        DateTime dt = DateUtil.parse(startTime, DatePattern.NORM_DATETIME_FORMAT);
        if(dt==null){
            return CommonResult.failed("请输入查询开始时间!");
        }
        List<String> list =  storeOrderService.queryOrderIds(dt);
        return CommonResult.success(list);
    }

    /**
     * 查询订单详情 - 只获取Buyer来源的商品
     * @param orderId
     * @return
     */
    @ApiOperation(value = "查询订单详情")
    @RequestMapping(value = "/orderDetail", method = RequestMethod.GET)
    public CommonResult<JSONObject> saveProduct(@RequestParam(value = "orderId") String orderId){
        // 有可能不是唯一，要想办法处理下
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderId);
        List<StoreOrderInfoVo> orderInfoVoList = storeOrderInfoService.getOrderListByOrderId(storeOrder.getId());

        if(null == storeOrder ||CollectionUtils.isEmpty(orderInfoVoList)){
           return CommonResult.failed("订单不存在!");
       }

       // 构造订单数据,懒得写bean了，先用json造一个调试吧
       JSONObject orderInfo = new JSONObject();
       List<JSONObject> productList = Lists.newArrayList();
       BigDecimal sourceCostTotal = new BigDecimal(0);

       //处理Sku信息
       dealOrderDetailSku(storeOrder, orderInfoVoList, productList, sourceCostTotal, orderInfo);

       if (CollectionUtils.isEmpty(productList)){
           LambdaUpdateWrapper<StoreOrder> updateWrapper = new LambdaUpdateWrapper();
           updateWrapper.eq(StoreOrder::getOrderId, orderId);
           updateWrapper.set(StoreOrder::getPushStatus, 2);
           updateWrapper.set(StoreOrder::getPushMessage, "该订单没有包含Buyer商品");
           storeOrderService.update(updateWrapper);
           log.warn(orderId +", 该订单没有包含Buyer商品!");
           return CommonResult.success(null);
       }

        //订单信息
        dealOrderInfo(storeOrder, orderInfo, orderId);

        //商品信息
        orderInfo.put("productList",productList);

       return CommonResult.success(orderInfo);
    }

    /**
     * 查询订单详情 - 处理Sku信息
     * @param storeOrder
     * @param orderInfo
     * @param orderId
     */
    private void dealOrderInfo(StoreOrder storeOrder, JSONObject orderInfo, String orderId) {
        orderInfo.put("orderId",orderId);
        orderInfo.put("payPostage",storeOrder.getPayPostage());
        orderInfo.put("payType",storeOrder.getPayType());
        orderInfo.put("shippingType",storeOrder.getShippingType());
        orderInfo.put("shippingFee",storeOrder.getPayPostage());
        orderInfo.put("shipperName","");
        orderInfo.put("shipperPhone","");
        orderInfo.put("shipperAddress","");
        orderInfo.put("createTime",storeOrder.getCreateTime());
        orderInfo.put("payTime",storeOrder.getPayTime());
    }

    /**
     * 查询订单详情 - 处理Order信息
     * @param storeOrder
     * @param orderInfoVoList
     * @param productList
     * @param sourceCostTotal
     */
    private void dealOrderDetailSku(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList, List<JSONObject> productList, BigDecimal sourceCostTotal, JSONObject orderInfo) {

        for (StoreOrderInfoVo info: orderInfoVoList){
            //不区分商品来源,收货地址处理
            dealUserAddress(storeOrder, info, orderInfo);

            JSONObject skuInfo = new JSONObject();
            String barCode = info.getInfo().getProductInfo().getBarCode();
            if (barCode.startsWith(BarCodeEnum.BUYER.getCode().toString())){
                String supplySource = barCode.substring(0,4);
                barCode = barCode.substring(4);

                skuInfo.put("productId",barCode);
                //此skuId必须为源数据的skuId
                skuInfo.put("sukId",info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId());
                skuInfo.put("stockArea",info.getInfo().getProductInfo().getStockArea());
                skuInfo.put("suk",info.getInfo().getProductInfo().getAttrInfo().getSuk());
                skuInfo.put("qty",info.getInfo().getCartNum());
                skuInfo.put("price",info.getInfo().getSourceCostPrice());
                //商品来源,暂时可以通过BarCode判断
                skuInfo.put("supplySource", supplySource);
                //skuInfo.put("supplySource",info.getInfo().getProductInfo().getMerId());

                productList.add(skuInfo);

                //商品数量
                Integer qty = info.getInfo().getCartNum();
                //商品成本价
                BigDecimal sourceCostPrice = info.getInfo().getSourceCostPrice();

                //计算推送的成本总价
                sourceCostTotal = sourceCostTotal.add(sourceCostPrice.multiply(new BigDecimal(qty)));
            }
        }

        // 第三方推送的成本总价 = 推送的成本价 * 商品数量
        orderInfo.put("payPrice", sourceCostTotal);
    }

    /**
     *  香港发大陆、欧洲发大陆 - 收货地址处理
     *  香港柴灣豐業街 4 號志同昌工業大廈 4 字樓 B 室(华安)　杨少峰/ 90541984
     */
    private void dealUserAddress(StoreOrder storeOrder, StoreOrderInfoVo info, JSONObject orderInfo) {

        //收货地址
        orderInfo.put("address",storeOrder.getUserAddress());
        orderInfo.put("consignee",storeOrder.getRealName());
        orderInfo.put("phone",storeOrder.getUserPhone());

        //收货地址区域类型 - 1:国内大陆
        Integer areaType = storeOrder.getAreaType();

        //收货地址: 大陆
        if(AreaTypeEnum.getTypeByCode(areaType).equals(AreaTypeEnum.CN)) {
            Integer tempId = info.getInfo().getProductInfo().getTempId();
            if (null != tempId){
                //发货地址: 2:香港发货、3:欧洲发货
                if (2==tempId||3==tempId){
                    orderInfo.put("address","香港柴灣豐業街 4 號志同昌工業大廈 4 字樓 B 室(华安)");
                    orderInfo.put("consignee","杨少峰");
                    orderInfo.put("phone","90541984");
                }
            }
        }

    }

    /**
     * 更新推送订单
     * @param storeRequest
     * @return
     */
    @ApiOperation(value = "更新推送订单")
    @RequestMapping(value = "/updatePushOrder", method = RequestMethod.POST)
    public CommonResult<JSONObject> updatePushOrder(@RequestBody @Validated PushOrderStoreRequest storeRequest){
        StoreOrder entity = new StoreOrder();
        LambdaUpdateWrapper<StoreOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreOrder::getOrderId, storeRequest.getOrderId());
        entity.setPushStatus(storeRequest.getPushStatus());
        entity.setPushMessage(storeRequest.getPushMessage());
        if (storeOrderService.update(entity, updateWrapper)){
            return CommonResult.success("更新推送订单成功!");
        }
        return CommonResult.failed("更新推送订单失败!");
    }

}



